package com.ydy.service.impl.center;

import com.ydy.constant.Const;
import com.ydy.mapper.UsersMapper;
import com.ydy.pojo.Users;
import com.ydy.pojo.bo.center.CenterUserBO;
import com.ydy.resource.ServerUri;
import com.ydy.service.center.CenterUserService;
import com.ydy.utils.DateUtil;
import com.ydy.utils.Sid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class CenterUserServiceImpl implements CenterUserService {

    public static final Logger log =
            LoggerFactory.getLogger(CenterUserServiceImpl.class);

    @Autowired
    public UsersMapper usersMapper;

    @Autowired
    private ServerUri serverUri;


    /**
     * 根据用户id获取用户信息
     * @param userId 用户id
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Users queryUserInfoByUserId(String userId) {
        log.info("根据用户id:{}获取用户信息",userId);
        Users user = usersMapper.selectByPrimaryKey(userId);
        // 由于浏览器可能存在缓存的情况，所以在这里，我们需要加上时间戳来保证更新后的图片可以及时刷新
        String finalUserFaceUrl = serverUri.appendImagUrl(user.getFace());
        user.setFace(finalUserFaceUrl);
        user.setPassword(null);
        return user;
    }

    /**
     * 根据用户id修改用户信息
     * @param userId 用户id
     * @param centerUserBO 用户对象信息
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Users updateUserInfo(String userId, CenterUserBO centerUserBO) {
        Users updateUser = new Users();
        BeanUtils.copyProperties(centerUserBO, updateUser);
        updateUser.setId(userId);
        updateUser.setUpdatedTime(new Date());
        log.info("根据用户id:{}更新用户信息",userId);
        usersMapper.updateByPrimaryKeySelective(updateUser);

        return queryUserInfoByUserId(userId);
    }

    /**
     * 根据用户id更新用户头像到数据库
     * @param userId 用户id
     * @param faceUrl 头像路径
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Users updateUserFaceByUserId(String userId, String faceUrl) {
        Users updateUser = new Users();
        updateUser.setId(userId);
        updateUser.setFace(faceUrl);
        updateUser.setUpdatedTime(new Date());

        log.info("根据用户id:{}更新用户头像信息:{}",userId,faceUrl);
        usersMapper.updateByPrimaryKeySelective(updateUser);
        return queryUserInfoByUserId(userId);
    }
}
